<template>
    <view class="profile-container">
        <!-- 头像部分 -->
        <view class="header-section">
            <view class="avatar-wrapper" @tap="chooseAvatar">
                <image :src="`http://127.0.0.1:8080/download/${userInfo.header}`" class="avatar"></image>
                <view class="edit-avatar">
                    <text class="iconfont icon-camera"></text>
                </view>
            </view>
            <text class="username">{{ userInfo.username || '未设置昵称' }}</text>
        </view>

        <!-- 信息列表 -->
        <view class="info-list">
            <view class="info-item" @tap="handleEditClick('username')">
                <text class="label">用户名</text>
                <view class="value-wrapper">
                    <text class="value">{{ userInfo.username || '未设置' }}</text>
                    <text class="iconfont icon-right"></text>
                </view>
            </view>

            <view class="info-item" @tap="handleEditClick('gender')">
                <text class="label">性别</text>
                <view class="value-wrapper">
                    <text class="value">{{ userInfo.gender || '未设置' }}</text>
                    <text class="iconfont icon-right"></text>
                </view>
            </view>

            <view class="info-item" @tap="handleEditClick('age')">
                <text class="label">年龄</text>
                <view class="value-wrapper">
                    <text class="value">{{ userInfo.age || '未设置' }}</text>
                    <text class="iconfont icon-right"></text>
                </view>
            </view>

            <view class="info-item" @tap="handleEditClick('email')">
                <text class="label">邮箱</text>
                <view class="value-wrapper">
                    <text class="value">{{ userInfo.email || '未设置' }}</text>
                    <text class="iconfont icon-right"></text>
                </view>
            </view>

            <view class="info-item" @tap="handleEditClick('password')">
                <text class="label">修改密码</text>
                <view class="value-wrapper">
                    <text class="value">******</text>
                    <text class="iconfont icon-right"></text>
                </view>
            </view>
        </view>

        <!-- 自定义弹窗 -->
        <view class="custom-popup" v-if="showPopup" @tap="closeEditPopup">
            <view class="popup-mask" :class="{ 'mask-show': showPopupAnimation }"></view>
            <view class="popup-content" :class="{ 'popup-show': showPopupAnimation }" @tap.stop>
                <view class="popup-title">{{ getPopupTitle() }}</view>
                <view class="popup-input-wrapper">
                    <!-- 根据当前编辑类型显示不同的输入控件 -->
                    <template v-if="currentEdit === 'gender'">
                        <picker 
                            @change="handleGenderChange" 
                            :value="genderIndex" 
                            :range="genderOptions"
                            class="picker-value"
                        >
                            <view class="picker-text">
                                {{ genderOptions[genderIndex] }}
                            </view>
                        </picker>
                    </template>
                    <template v-else-if="currentEdit === 'password'">
                        <input 
                            type="password" 
                            v-model="passwordForm.oldPassword" 
                            placeholder="请输入原密码"
                            class="popup-input"
                        />
                        <input 
                            type="password" 
                            v-model="passwordForm.newPassword" 
                            placeholder="请输入新密码"
                            class="popup-input"
                        />
                        <input 
                            type="password" 
                            v-model="passwordForm.confirmPassword" 
                            placeholder="请确认新密码"
                            class="popup-input"
                        />
                    </template>
                    <template v-else>
                        <input 
                            :type="getInputType()"
                            v-model="editValue"
                            :placeholder="getPlaceholder()"
                            class="popup-input"
                        />
                    </template>
                </view>
                <view class="error-message" v-if="errorMessage">{{ errorMessage }}</view>
                <view class="popup-buttons">
                    <button class="popup-btn cancel" @tap="closeEditPopup">取消</button>
                    <button class="popup-btn confirm" @tap="handleConfirm">确认</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import API from '@/api/config.js'

export default {
    data() {
        return {
            userInfo: {
                header: '',
                username: '',
                gender: '',
                age: '',
                email: ''
            },
            genderOptions: ['男', '女'],
            genderIndex: 0,
            passwordForm: {
                oldPassword: '',
                newPassword: '',
                confirmPassword: ''
            },
            currentEdit: '',
            editValue: '',
            showPopup: false,
            showPopupAnimation: false,
            errorMessage: ''
        }
    },
    onLoad() {
        this.loadUserInfo()
    },
    methods: {
        async loadUserInfo() {
            try {
                const token = uni.getStorageSync('token')
                const res = await uni.request({
                    url: API.USER_INFO,
                    method: 'GET',
                    header: { 'Authorization': token }
                })
                
                if (res.data.code === 200) {
                    this.userInfo = res.data.data
                    this.genderIndex = this.genderOptions.indexOf(this.userInfo.gender) || 0
                }
            } catch (error) {
                console.error('获取用户信息失败:', error)
                uni.showToast({
                    title: '获取信息失败',
                    icon: 'none'
                })
            }
        },

        handleEditClick(type) {
            try {
                this.currentEdit = type
                this.editValue = this.userInfo[type] || ''
                this.errorMessage = ''
                
                if (type === 'gender') {
                    this.genderIndex = this.genderOptions.indexOf(this.userInfo.gender) || 0
                }
                
                if (type === 'password') {
                    this.passwordForm = {
                        oldPassword: '',
                        newPassword: '',
                        confirmPassword: ''
                    }
                }
                
                this.showPopup = true
                setTimeout(() => {
                    this.showPopupAnimation = true
                }, 50)
                
            } catch (error) {
                console.error('打开编辑弹窗失败:', error)
                uni.showToast({
                    title: '操作失败，请重试',
                    icon: 'none'
                })
            }
        },

        closeEditPopup() {
            try {
                this.showPopupAnimation = false
                this.errorMessage = ''
                setTimeout(() => {
                    this.showPopup = false
                    this.currentEdit = ''
                    this.editValue = ''
                }, 200)
            } catch (error) {
                console.error('关闭弹窗失败:', error)
                this.showPopup = false
                this.showPopupAnimation = false
            }
        },

        async handleConfirm() {
            try {
                if (this.currentEdit === 'password') {
                    await this.confirmChangePassword()
                } else {
                    await this.confirmEdit()
                }
            } catch (error) {
                console.error('确认修改失败:', error)
                this.errorMessage = '操作失败，请重试'
                uni.showToast({
                    title: '操作失败，请重试',
                    icon: 'none'
                })
            }
        },

        getPopupTitle() {
            const titles = {
                username: '修改用户名',
                gender: '修改性别',
                age: '修改年龄',
                email: '修改邮箱',
                password: '修改密码'
            }
            return titles[this.currentEdit] || '修改信息'
        },

        getInputType() {
            if (this.currentEdit === 'age') return 'number'
            if (this.currentEdit === 'email') return 'email'
            return 'text'
        },

        getPlaceholder() {
            const placeholders = {
                username: '请输入用户名',
                age: '请输入年龄',
                email: '请输入邮箱'
            }
            return placeholders[this.currentEdit] || '请输入'
        },

        async confirmEdit() {
            if (!this.validateEdit()) return
            
            try {
                console.log('开始修改信息:', this.currentEdit, this.editValue) // 调试日志
                
                // 构建完整的用户信息对象
                const updateData = JSON.stringify({
                    ...this.userInfo,  // 保持其他字段不变
                    [this.currentEdit]: this.currentEdit === 'age' ? 
                        parseInt(this.editValue) : 
                        this.currentEdit === 'gender' ? 
                            this.genderOptions[this.genderIndex] : 
                            this.editValue
                })
                
                console.log('发送的数据:', updateData) // 调试日志
                
                const res = await uni.request({
                    url: API.USER_UPDATE,
                    method: 'POST',
                    data: updateData,
                    header: {
                        'Authorization': uni.getStorageSync('token'),
                        'Content-Type': 'application/json'
                    }
                })
                
                console.log('修改响应:', res.data) // 调试日志
                
                if (res.data.code === 200) {
                    // 更新成功
                    this.userInfo[this.currentEdit] = this.currentEdit === 'gender' ? 
                        this.genderOptions[this.genderIndex] : this.editValue
                    
                    uni.showToast({
                        title: '修改成功',
                        icon: 'success'
                    })
                    this.closeEditPopup()
                } else {
                    this.errorMessage = res.data.message || '修改失败，请重试'
                    uni.showToast({
                        title: this.errorMessage,
                        icon: 'none'
                    })
                }
            } catch (error) {
                console.error('修改信息失败:', error)
                this.errorMessage = '网络错误，请稍后重试'
                uni.showToast({
                    title: this.errorMessage,
                    icon: 'none'
                })
            }
        },

        validateEdit() {
            this.errorMessage = ''

            if (!this.editValue && this.currentEdit !== 'gender') {
                this.errorMessage = '请输入内容'
                uni.showToast({
                    title: this.errorMessage,
                    icon: 'none'
                })
                return false
            }
            
            if (this.currentEdit === 'email') {
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
                if (!emailRegex.test(this.editValue)) {
                    this.errorMessage = '请输入正确的邮箱格式'
                    uni.showToast({
                        title: this.errorMessage,
                        icon: 'none'
                    })
                    return false
                }
            }
            
            if (this.currentEdit === 'age') {
                const age = parseInt(this.editValue)
                if (isNaN(age) || age < 1 || age > 120) {
                    this.errorMessage = '请输入有效年龄'
                    uni.showToast({
                        title: this.errorMessage,
                        icon: 'none'
                    })
                    return false
                }
            }
            
            return true
        },

        async chooseAvatar() {
            try {
                const res = await uni.chooseImage({
                    count: 1,
                    sizeType: ['compressed']
                })
                
                // 上传头像
                const uploadRes = await uni.uploadFile({
                    url: API.UPLOAD_AVATAR,
                    filePath: res.tempFilePaths[0],
                    name: 'file',
                    header: {
                        'Authorization': uni.getStorageSync('token')
                    }
                })
                
                const result = JSON.parse(uploadRes.data)
                if (result.code === 200) {
                    this.userInfo.header = result.data
                    uni.showToast({ title: '头像更新成功' })
                }
            } catch (error) {
                console.error('上传头像失败:', error)
                uni.showToast({ title: '上传失败，请重试', icon: 'none' })
            }
        },

        handleGenderChange(e) {
            this.genderIndex = e.detail.value
            this.userInfo.gender = this.genderOptions[this.genderIndex]
        },

        async confirmChangePassword() {
            if (!this.validatePassword()) return
            
            try {
                console.log('开始修改密码') // 调试日志
                
                const passwordData = JSON.stringify({
                    oldPassword: this.passwordForm.oldPassword,
                    newPassword: this.passwordForm.newPassword
                })
                
                const res = await uni.request({
                    url: API.CHANGE_PASSWORD,
                    method: 'POST',
                    data: passwordData,
                    header: {
                        'Authorization': uni.getStorageSync('token'),
                        'Content-Type': 'application/json'
                    }
                })
                
                console.log('密码修改响应:', res.data) // 调试日志
                
                if (res.data.code === 200) {
                    uni.showToast({
                        title: '密码修改成功',
                        icon: 'success'
                    })
                    this.closeEditPopup()
                } else {
                    this.errorMessage = res.data.message || '修改失败，请重试'
                    uni.showToast({
                        title: this.errorMessage,
                        icon: 'none'
                    })
                }
            } catch (error) {
                console.error('修改密码失败:', error)
                this.errorMessage = '网络错误，请稍后重试'
                uni.showToast({
                    title: this.errorMessage,
                    icon: 'none'
                })
            }
        },

        validatePassword() {
            if (!this.passwordForm.oldPassword) {
                this.errorMessage = '请输入原密码'
                uni.showToast({
                    title: this.errorMessage,
                    icon: 'none'
                })
                return false
            }
            if (!this.passwordForm.newPassword) {
                this.errorMessage = '请输入新密码'
                uni.showToast({
                    title: this.errorMessage,
                    icon: 'none'
                })
                return false
            }
            if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
                this.errorMessage = '两次密码输入不一致'
                uni.showToast({
                    title: this.errorMessage,
                    icon: 'none'
                })
                return false
            }
            return true
        }
    }
}
</script>

<style>
.profile-container {
    min-height: 100vh;
    background-color: #1a1a1a;
    padding-bottom: 40rpx;
}

.header-section {
    background: linear-gradient(135deg, #2c2c2c, #1a1a1a);
    padding: 60rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    border-bottom: 1px solid #333;
}

.avatar-wrapper {
    position: relative;
    margin-bottom: 20rpx;
}

.avatar {
    width: 160rpx;
    height: 160rpx;
    border-radius: 80rpx;
    border: 4rpx solid #333;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.3);
}

.edit-avatar {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 48rpx;
    height: 48rpx;
    background: #2c2c2c;
    border-radius: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
    border: 1px solid #444;
}

.username {
    color: #e0e0e0;
    font-size: 32rpx;
    font-weight: 500;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

.info-list {
    margin: 20rpx;
    background: #2c2c2c;
    border-radius: 20rpx;
    padding: 0 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
}

.info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 20rpx;
    border-bottom: 1rpx solid #333;
}

.info-item:last-child {
    border-bottom: none;
}

.label {
    font-size: 28rpx;
    color: #e0e0e0;
}

.value-wrapper {
	
    display: flex;
    align-items: center;
}

.value {
    font-size: 28rpx;
    color: #999;
    margin-right: 10rpx;
}

.icon-right {
    font-size: 24rpx;
    color: #999999;
}

.custom-popup {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
}

.popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0);
    transition: all 0.2s ease-out;
}

.mask-show {
    background-color: rgba(0, 0, 0, 0.5);
}

.popup-content {
    position: relative;
    background: #1e1e1e;
    border-radius: 20rpx;
    width: 600rpx;
    padding: 40rpx 30rpx;
    transform: scale(0.8);
    opacity: 0;
    transition: all 0.2s ease-out;
    z-index: 1000;
    border: 1px solid #444;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.3),
                0 0 0 1px rgba(255, 255, 255, 0.05);
}

.popup-show {
    transform: scale(1);
    opacity: 1;
}

.popup-title {
    color: #f0f0f0;
    font-size: 32rpx;
    font-weight: 500;
    margin-bottom: 40rpx;
    letter-spacing: 2rpx;
}

.popup-input-wrapper {
    margin-bottom: 40rpx;
    padding: 0 20rpx;
}

.popup-input {
    width: 90%;
    height: 88rpx;
    background: #242424;
    border-radius: 12rpx;
    padding: 0 36rpx;
    font-size: 28rpx;
    margin-bottom: 24rpx;
    border: 1px solid #383838;
    transition: all 0.3s ease;
    color: #e0e0e0;
    box-shadow: inset 0 2rpx 8rpx rgba(0, 0, 0, 0.2),
                0 2rpx 4rpx rgba(255, 255, 255, 0.03);
}

.popup-input.error {
    border-color: #ff4d4f;
    background: #fff1f0;
}

.popup-input:focus {
    background: #2a2a2a;
    border-color: #505050;
    box-shadow: inset 0 2rpx 8rpx rgba(0, 0, 0, 0.1),
                0 0 0 2rpx rgba(255, 255, 255, 0.05);
}

.popup-input::placeholder {
    color: #666;
    font-size: 26rpx;
}

.popup-buttons {
    display: flex;
    justify-content: space-between;
    gap: 20rpx;
}

.popup-btn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 40rpx;
    font-size: 28rpx;
    transition: all 0.2s ease;
}

.popup-btn.cancel {
    background: #333;
    color: #e0e0e0;
    border: 1px solid #444;
}

.popup-btn.cancel:active {
    background: #444;
}

.popup-btn.confirm {
    background: linear-gradient(135deg, #444, #333);
    color: #FFFFFF;
    border: 1px solid #555;
}

.popup-btn.confirm:active {
    transform: scale(0.98);
}

.picker-value {
    padding: 10rpx 20rpx;
    width: 90%;
    height: 88rpx;
    background: #1a1a1a;
    border-radius: 16rpx;
    transition: all 0.3s ease;
    border: 1px solid #444;
    box-shadow: inset 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.picker-text {
    line-height: 88rpx;
    padding: 0 36rpx;
    color: #e0e0e0;
}

.error-message {
    color: #ff4d4f;
    font-size: 24rpx;
    text-align: center;
    margin: -20rpx 0 20rpx;
    min-height: 24rpx;
}

input[type="password"] {
    letter-spacing: 4rpx;
}
</style> 